package com.lnj.community.controller;

import com.lnj.community.dao.entity.Comment;
import com.lnj.community.dao.entity.DiscussPost;
import com.lnj.community.dao.entity.Event;
import com.lnj.community.dao.entity.Page;
import com.lnj.community.event.EventProduct;
import com.lnj.community.service.CommentService;
import com.lnj.community.service.DiscussPostService;
import com.lnj.community.service.LikeService;
import com.lnj.community.service.UserService;
import com.lnj.community.utiles.CommunityConstant;
import com.lnj.community.utiles.HostHolder;
import com.lnj.community.utiles.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.*;

@Controller
@RequestMapping("/comment")
public class CommentController implements CommunityConstant {
    @Autowired
    private CommentService commentService;
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private EventProduct eventProducer;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private LikeService likeService;

    /**
     * 添加评论
     */
    @RequestMapping(path = "/add/{discussPostId}", method = RequestMethod.POST)
    public String addComment(@PathVariable("discussPostId") int discussPostId, Comment comment) {
        comment.setUserId(HostHolder.getUser().getId());
        comment.setStatus(0);
        comment.setCreateTime(new Date());
        //插入评论
        commentService.addComment(comment);

        //触发评论事件 往Kafka中发送消息 评论
        Event event = new Event()
                //主题类型
                .setTopic(TOPIC_COMMENT)
                //评论的用户id
                .setUserId(HostHolder.getUser().getId())
                //评论的类型 帖子 评论 回复
                .setEntityType(comment.getEntityType())
                //评论的id
               .setEntityId(comment.getEntityId())
                //评论的作者Id
               .setEntityUserId(comment.getUserId())
                //评论的帖子id
               .setData("postId", discussPostId);
        //判断评论的目标实体是什么
        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            DiscussPost target = discussPostService.findDiscussPostById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        } else if (comment.getEntityType() == ENTITY_TYPE_COMMENT) {
            Comment target = commentService.findCommentById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        }
        //给评论的作者发消息 有可能是评论的作者 也有可能是回复的作者
        eventProducer.fireEvent(event);

        //触发发帖事件 把帖子的最新数据插入到Elasticsearch中 异步处理
        if (comment.getEntityType() == ENTITY_TYPE_POST) {
             event=new Event()
                    .setTopic(TOPIC_PUBLISH)
                    .setUserId(HostHolder.getUser().getId())
                    .setEntityType(ENTITY_TYPE_POST)
                    .setEntityId(discussPostId);
             //对于是评论的帖子 要把帖子的分数计算 先把帖子的id存到Redis中 然后在定时任务中计算分数
             String redisKey = RedisKeyUtil.getPostScoreKey();
             redisTemplate.opsForSet().add(redisKey, discussPostId);

        }else if (comment.getEntityType() == ENTITY_TYPE_COMMENT) {
             event=new Event()
                    .setTopic(TOPIC_PUBLISH)
                    .setUserId(comment.getUserId())
                    .setEntityType(ENTITY_TYPE_COMMENT)
                    .setEntityId(discussPostId);
        }
        eventProducer.fireEvent(event);

        //重定向到帖子详情页面
        return "redirect:/discuss/detail/" + discussPostId;
    }

    /**
     * 根据用户id查询用户的评论
     */
    @RequestMapping(path = "/myReply/{userId}", method = RequestMethod.GET)
    public String getCommentByUserId(@PathVariable("userId") int userId, Model model, Page page) {
        // 设置分页信息
        page.setLimit(5);
        page.setPath("/comment/myReply/" + userId);
        page.setRows(commentService.findCommentCountByUserId(userId));

        //查询用户的评论
        List<Comment> commentList = commentService.findCommentByUserId(userId);
        List<Map<String, Object>> commentVoList = new ArrayList<>();
        if (commentList != null) {
            for (Comment comment : commentList) {
                Map<String, Object> commentVo = new HashMap<>();
                //评论
                commentVo.put("comment", comment);
                if (comment.getEntityType() == ENTITY_TYPE_POST) {
                    //评论的帖子
                    DiscussPost discussPost = discussPostService.findDiscussPostById(comment.getEntityId());
                    commentVo.put("discussPost", discussPost);
                }else if (comment.getEntityType() == ENTITY_TYPE_COMMENT) {
                    Comment comment1 = commentService.findCommentById(comment.getEntityId());
                    commentVo.put("target", comment1);
                }
                //评论的点赞
                long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeCount", likeCount);
                //评论的回复数量
                commentVo.put("replyCount", commentService.findCommentCount(comment.getId()));
                commentVoList.add(commentVo);
            }
            model.addAttribute("commentVoList", commentVoList);
            model.addAttribute("commentCount", commentVoList.size());
        }

        return "site/my-reply";
    }

}
